package com.hsmw.api.controller.pub;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hsmw.api.service.*;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.HsmwOrderVehicleRelation;
import com.hsmw.domain.HsmwPaths;
import com.hsmw.domain.HsmwUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Auther: wd
 * @Date 2021-04-30
 * @Description: websocket 服务类
 */

/**
 *
 * @ServerEndpoint 这个注解有什么作用？
 *
 * 这个注解用于标识作用在类上，它的主要功能是把当前类标识成一个WebSocket的服务端
 * @Param name
 * 注解的值用户客户端连接访问的URL地址
 *
 */

@Slf4j
@Component
@ServerEndpoint("/websocket/{name}")
public class WebSocket {


    @Autowired
    public HsmwOrderVehicleRelationService hsmwOrderVehicleRelationService;

    @Autowired
    public HsmwPathsService hsmwPathsService;


    static HsmwVehicleService hsmwVehicleService;
    @Autowired
    public void setHsmwUserService(HsmwVehicleService hsmwVehicleService){
        this.hsmwVehicleService=hsmwVehicleService;
    }


    static  HsmwUserService hsmwUserService;

    @Autowired
    public void setHsmwUserService(HsmwUserService hsmwUserService){
        this.hsmwUserService=hsmwUserService;
    }





    /**
     *  与某个客户端的连接对话，需要通过它来给客户端发送消息
     */
    private Session session;

    /**
     * 标识当前连接客户端的用户名
     */
    private String name;

    /**
     *  用于存所有的连接服务的客户端，这个对象存储是安全的
     */
    public static ConcurrentHashMap<String,WebSocket> webSocketSet = new ConcurrentHashMap<>();

    public static ConcurrentHashMap<String, WebSocket> getWebSocketSet() {
        return webSocketSet;
    }

    public static void setWebSocketSet(ConcurrentHashMap<String, WebSocket> webSocketSet) {
        WebSocket.webSocketSet = webSocketSet;
    }

    @OnOpen
    public void OnOpen(Session session, @PathParam(value = "name") String name){
        this.session = session;
        this.name = name;
        //name是用来表示唯一客户端，如果需要指定发送，需要指定发送通过name来区分
        webSocketSet.put(name,this);
        log.info("[WebSocket] 连接成功，当前连接人数为：={}",webSocketSet.size());
       // System.out.println("[WebSocket] 连接成功，当前连接人数为：={}="+webSocketSet.size());
        AppointSending(name,"当前连接人数为：="+webSocketSet.size());

    }

    @OnClose
    public void OnClose(){
        webSocketSet.remove(this.name);
        log.info("[WebSocket] 退出成功，当前连接人数为：={}",webSocketSet.size());
        //System.out.println("[WebSocket] 退出成功，当前连接人数为：={}="+webSocketSet.size());

    }

    @OnMessage
    public void OnMessage(String message){
        //System.out.println("[WebSocket] 收到消息：{}"+ name +message);
        //log.info("[WebSocket] 收到消息：{}",name +"-----"+message);
        AppointSending(name,"我收到了");
        //判断是否需要指定发送，具体规则自定义
        if(StringUtils.isNotBlank(message)){
           JSONObject msg = JSONObject.parseObject(message);
            SocketInfoEntity entity = JSON.toJavaObject(msg,SocketInfoEntity.class);
            if(StringUtils.isNotBlank(entity.getMsgType())&& "location".equals(entity.getMsgType())){
                //获取的用于在手机端同步 手机位置信息 到车辆信息表
                HsmwUser user = hsmwUserService.findByUsername(name);
                if(StringUtils.isNotNull(user)){
                    HashMap param = new HashMap();
                    param.put("location",entity.getLocation());
                    param.put("userId",user.getId());
                    param.put("direct",entity.getDirect());
                    hsmwVehicleService.updateMobileLocation(param);
                }
            }
        }
    }

    @OnError
    public void OnError(Session session,Throwable throwable){
        throwable.printStackTrace();
    }


    /**
     * 群发
     * @param message
     */
    public void GroupSending(String message, List<String> userList){
        for (String name : userList){
            try {
                WebSocket webSocket = webSocketSet.get(name);
                if(StringUtils.isNotNull(webSocket)){
                    webSocket.session.getBasicRemote().sendText(message);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 指定发送
     * @param name
     * @param message
     */
    public  void AppointSending(String name,String message){
        try {
            System.out.println(webSocketSet.values().toString());
            WebSocket webSocket = webSocketSet.get(name);
            if(StringUtils.isNotNull(webSocket)){
                synchronized (webSocket){
                    webSocket.session.getBasicRemote().sendText(message);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 判断是否断开连接，断开返回true,没有返回false
     * @param socket
     * @return
     */
    public Boolean isServerClose(WebSocket socket){
        try{
            return false;
        }catch(Exception se){
            return true;
        }
    }
}